package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"tie/global"
	"tie/pkg"
)

type ChatHandler struct {
	websocket *pkg.Websocket
}

func NewChat() ChatHandler {
	return ChatHandler{
		websocket: pkg.NewWebsocket(),
	}
}

func (ch *ChatHandler) Chat(r *gin.Context) {
	uid := r.Query("userId")
	userId, err := strconv.Atoi(uid)
	if err != nil {
		return
	}
	upgrade, err := global.Upgrader.Upgrade(r.Writer, r.Request, nil)
	if err != nil {
		return
	}
	node := global.Node{
		Conn: upgrade,
		Data: make(chan []byte, 50),
	}
	global.ClientMap[int64(userId)] = node

	go pkg.WriteMessage(node)
	go pkg.ReadMessage(node)
}
